package com.dz.risk.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;

/**
 * mybatis参数设置
 *
 * @author Doke
 * @date 2021/8/5
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增数据处理
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();

        //接入用户信息时,设置成当前用户ID
        String userId = null;
        HttpServletRequest request = null;

        if (Objects.nonNull(requestAttributes)) {
            request = requestAttributes.getRequest();
        }

        this.setFieldValByName("createdUser", StringUtils.isEmpty(userId) ? "admin" : userId, metaObject);
        this.setFieldValByName("updatedUser", StringUtils.isEmpty(userId) ? "admin" : userId, metaObject);
    }

    /**
     * 更新数据处理
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();

        //接入用户信息时,设置成当前用户ID
        String userId = null;
        HttpServletRequest request = null;

        if (Objects.nonNull(requestAttributes)) {
            request = requestAttributes.getRequest();
        }

        this.setFieldValByName("updatedUser", StringUtils.isEmpty(userId) ? "admin" : userId, metaObject);
    }
}
